#include "recordedtime.h"

#include <QTimer>
#include <QFile>
#include <QTextStream>
#include <QObject>


RecordedTime::RecordedTime(int order, int elapsedTime, QString note) :
        mOrder(order),
        mNote(note),
        mElapsedTime(elapsedTime),
        mWarning(false),
        mHide(false)
{
}

QList<QStandardItem*>
RecordedTime::standardItemList()
{
    qDebug("getting standard list of record time %d (mWarning=%d)", mOrder, mWarning);
    QList<QStandardItem*> items;

    QStandardItem *countItem = new QStandardItem(QString().setNum(mOrder));
    //countItem->setData(QVariant(this));
    QStandardItem *timeItem = new QStandardItem(RecordedTime::calculateTimeString(mElapsedTime));
    if (hasWarning())
        timeItem->setBackground(QBrush(QColor("#FFFF55")));
    //timeItem->setData(QVariant(this));
    QString note = mNote;
    if (hasWarning())
        note += " [???]";
    QStandardItem *noteItem = new QStandardItem(note);

    //noteItem->setData(QVariant(this));

    if (mHide) {
        countItem->setEnabled(false);
        timeItem->setEnabled(false);
        noteItem->setEnabled(false);
    }

    countItem->setTextAlignment(Qt::AlignRight);
    items << countItem << timeItem << noteItem;
    return items;
}

int RecordedTime::order()
{
    return mOrder;
}

QString RecordedTime::note()
{
    return mNote;
}

QString RecordedTime::time()
{
    return RecordedTime::calculateTimeString(mElapsedTime);
}

QString RecordedTime::roundedTime()
{
    return RecordedTime::calculateRoundedTimeString(mElapsedTime);
}

int RecordedTime::elapsedMSecs()
{
    return mElapsedTime;
}

bool RecordedTime::hasWarning()
{
    return mWarning;
}

void RecordedTime::toggleWarning()
{
    qDebug("toggleWarning");
    if (mWarning)
        mWarning = false;
    else
        mWarning = true;
}

/* static */
QString RecordedTime::calculateTimeString(int elapsed)
{
    int totalSecs = (int)(elapsed / 1000);
    int mins = (int)(elapsed / 1000 / 60);
    int secs = int((elapsed/60000.0 - mins) * 60);
    int ms = int((elapsed/1000.0 - totalSecs) * 100);

    QString elapsedTimeString;
    elapsedTimeString.sprintf("%02d:%02d.%02d", mins, secs, ms);
    return elapsedTimeString;
}

/* static */
QString RecordedTime::calculateRoundedTimeString(int elapsed)
{
    int totalSecs = (int)(elapsed / 1000);
    int mins = (int)(elapsed / 1000 / 60);
    int secs = int((elapsed/60000.0 - mins) * 60);
    int ms = int((elapsed/1000.0 - totalSecs) * 100);

    if ( ms > 50 ) {
        secs +=1;
        if (secs == 60)
            mins += 1;
    }

    QString elapsedTimeString;
    elapsedTimeString.sprintf("%02d:%02d", mins, secs);
    return elapsedTimeString;
}
